package com.rongshu.sendmessage.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.CircleOptions;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.BusinessArea;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.nostra13.universalimageloader.utils.L;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.adapter.AddressAdapter;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.LocationInfo;
import com.rongshu.sendmessage.util.DialogUtil;
import com.rongshu.sendmessage.util.ObjectUtils;
import com.rongshu.sendmessage.util.PermissionUtils;
import com.rongshu.sendmessage.util.StringUtils;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.httpUtil.HYContent;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

public class DingWeiActivity extends BaseActivity implements
        AMap.OnMarkerClickListener,
        AMap.OnMapLoadedListener,
        AMap.OnMapClickListener,
        LocationSource,
//        AMapLocationListener,
        PoiSearch.OnPoiSearchListener,
//        AMap.OnMarkerDragListener,
        GeocodeSearch.OnGeocodeSearchListener,
        AMap.OnCameraChangeListener
{
    private MapView mMapView;
    private AMap mAMap;
    private Marker mGPSMarker;    //定位位置显示
//    private AMapLocation location;
    private OnLocationChangedListener mListener;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    //你编码对象
    private GeocodeSearch geocoderSearch;
    Button ivReturn;
    private MarkerOptions markOptions;
    private LatLng latLng;
    private String addressName;
    private BottomSheetBehavior mBehavior;
    RelativeLayout bottomSheet;
    private String latlugStr;
    private ListView mListView;
    private ArrayList<LocationInfo> mList;
    private AddressAdapter mAdapter;
    private String deepType="";
    private String city;
    private PoiSearch.Query query;
    private PoiSearch poiSearch;
    private String keyword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dina_wei);
        mContext=this;
        ButterKnife.bind(this);
        initMap(savedInstanceState);
        checkLocation(0);
    }
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_return) {
            finish();
        } else if (id == R.id.btn_ok) {
            Intent intent = new Intent();
            LocationInfo locationInfo = null;
            for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).isSelect()){
                    locationInfo = mList.get(i);
                }
            }
            if (locationInfo==null){
                ToastUtils.show(mContext,"请先选择地址后重试！");
                return;
            }
            String str=locationInfo.getAllAddress()+locationInfo.getTitle();
            intent.putExtra("address",str);
            intent.putExtra("latlugStr", locationInfo.getLonTitude()+","+locationInfo.getLatitude());
            setResult(90, intent);
            finish();
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initMap(Bundle savedInstanceState) {

        ivReturn=findViewById(R.id.iv_return);
        EditText et_search = findViewById(R.id.et_search);
        et_search.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //点击搜索的时候隐藏软键盘

                ObjectUtils.hideKeyboard(et_search);
                if(StringUtils.isEmpty(keyword)){
                    return false;
                }
                doSearchQuery();
//                // 在这里写搜索的操作,一般都是网络请求数据
//                PoiSearch.Query query = new PoiSearch.Query(keyword, "生活服务", "");
//                query.setPageSize(20);
//                PoiSearch search = new PoiSearch(this, query);
//                search.setBound(new PoiSearch.SearchBound(new LatLonPoint(location.getLatitude(), location.getLongitude()), 10000));
//                search.setOnPoiSearchListener(this);
//                search.searchPOIAsyn();
                return true;
            }
            return false;
        });
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if (s!=null&& !StringUtils.isBlank(s.toString())){
                    keyword=s.toString();
                }else{
                    keyword="";
                }
            }
        });
//        ScrollView scrollView = findViewById(R.id.scrollView);
        mList=new ArrayList<>();
        mListView= findViewById(R.id.listView);
        mAdapter=new AddressAdapter(mContext,mList);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener((parent, view, position, id) -> {
            for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).isSelect()){
                    mList.get(i).setSelect(false);
                }
            }
            mList.get(position).setSelect(true);
            mAdapter.setList(mList);
            mAdapter.notifyDataSetChanged();
            LatLng la = new LatLng(mList.get(position).getLatitude(),
                    mList.get(position).getLonTitude());
            mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(la,14), 1000, null);
//            mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(la, 14));
            //latitude

        });
//        tvLnt=(TextView)findViewById(R.id.tv_lnt);

        mMapView =  findViewById(R.id.map);

        mMapView.onCreate(savedInstanceState);
        try{
            geocoderSearch = new GeocodeSearch(this);
        }catch (Exception e){
            e.printStackTrace();
        }

        mAMap = mMapView.getMap();
        // 设置定位监听
        mAMap.setOnMapLoadedListener(this);
        mAMap.setOnMarkerClickListener(this);
        mAMap.setOnMapClickListener(this);

        mAMap.setLocationSource(this);
        //设置地图拖动监听
        mAMap.setOnCameraChangeListener(this);
        // 绑定marker拖拽事件
//        mAMap.setOnMarkerDragListener(this);
        //逆编码监听事件
        geocoderSearch.setOnGeocodeSearchListener(this);
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.navi_map_gps_locked));// 设置小蓝点的图标
        //myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(0f);// 设置圆形的边框粗细
        myLocationStyle.anchor(0.5f, 0.7f);
        myLocationStyle.showMyLocation(false);
//        myLocationStyle.showMyLocation(false);
        mAMap.setMyLocationStyle(myLocationStyle);
        //添加一个圆
        CircleOptions circleOptions = new CircleOptions();
        circleOptions.radius(20.0f);
        mAMap.addCircle(circleOptions);
        //设置amap的属性
        UiSettings settings = mAMap.getUiSettings();
        settings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        //开启放缩手势
        settings.setZoomGesturesEnabled(true);
        //开启滑动手势
        settings.setScrollGesturesEnabled(true);
        //开启全部手势
        settings.setAllGesturesEnabled(true);
        String latitude = MyApplication.mSettings.getString(HYContent.Latitude, "");
        String longitude =MyApplication.mSettings.getString(HYContent.Longitude,"");
        addressName =MyApplication.mSettings.getString(HYContent.ADDRESS,"");
        city =MyApplication.mSettings.getString(HYContent.CITY,"");
        double latitudeD=0;
        double longitudeD=0;
        try {
            latitudeD=Double.parseDouble(latitude);
            longitudeD=Double.parseDouble(longitude);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(longitudeD==0){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                PermissionUtils permissionUtils = new PermissionUtils(this, mContext);
                permissionUtils.requestMultiPermissions(requestCode -> {
                    setLocation();
                });
            }else{
                setLocation();

            }
            return;
        }
        latLng = new LatLng(latitudeD, longitudeD);
        setMarket(latLng, city, addressName);
        latlugStr=longitude + "," +latitude ;
//        mListener.onLocationChanged(location);// 显示系统箭头
        getAddressByLatlng(latitudeD,longitudeD);
//        mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14), 1000, null);

        mAMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,14));
        doSearchQuery();
        mAMap.setMyLocationEnabled(false);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }
//    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        listView.requestDisallowInterceptTouchEvent(true);
//        return super.dispatchTouchEvent(ev);
//    }
    private void checkLocation(int i) {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        // 判断GPS模块是否开启，如果没有则开启
        if (!locationManager
                .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            DialogUtil.showTextDialog(mContext, "请打开GPS", "打开GPS更好的体验应用哦", false, new DialogUtil.OnDialogListener<Void>() {
                @Override
                public void onPositiveButtonClick(Void aVoid) {
                    // 转到手机设置界面，用户设置GPS
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, 123); // 设置完成后返回到原来的界面
                }

                @Override
                public void onNegativeButtonClick(Void aVoid) {

                }
            });
        }else{
            if (i==1)
                setLocation();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==123){
            checkLocation(1);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        setLocation();
    }

    private void setLocation() {
        //初始化定位
        AMapLocationClient mLocationClient = new AMapLocationClient(mContext);
        //设置定位回调监听
        mLocationClient.setLocationListener(new AMapLocationListener(){

            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                double latitudeD=aMapLocation.getLatitude();
                double longitudeD=aMapLocation.getLongitude();
                latLng = new LatLng(latitudeD, longitudeD);
                setMarket(latLng, city, addressName);
                MyApplication.editor.putString(HYContent.Latitude, latitudeD+"");
                MyApplication.editor.putString(HYContent.Longitude,longitudeD+"");
                MyApplication.editor.commit();
                latlugStr=aMapLocation.getLatitude() + "," +aMapLocation.getLongitude() ;
                getAddressByLatlng(latitudeD,longitudeD);
//                mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15), 1000, null);

                mAMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                doSearchQuery();
                mAMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
            }
        });

        //初始化定位参数
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式、、Hight_Accuracy默认的
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

//    @Override
//    public void onLocationChanged(AMapLocation aMapLocation) {
//        if (mListener != null && aMapLocation != null)
//        {
//            if (aMapLocation != null && aMapLocation.getErrorCode() == 0)
//            {
//                mListener.onLocationChanged(aMapLocation);// 显示系统箭头
//                LatLng la = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
//                setMarket(la, aMapLocation.getCity(), aMapLocation.getAddress());
//                mLocationClient.stopLocation();
//                //显示位置、经纬度
//                //获取当前经纬度坐标
//                addressName=aMapLocation.getAddress();
////                tvAdress.setText(addressName);
//                latlugStr=aMapLocation.getLongitude() + "," + aMapLocation.getLatitude();
////                tvLnt.setText(latlugStr);
//                getAddressByLatlng(aMapLocation.getLongitude(),aMapLocation.getLatitude());
//                mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(la, 14), 1000, null);
//                city = aMapLocation.getProvince();
//                doSearchQuery();
////                PoiSearch.Query query = new PoiSearch.Query("", "生活服务", "");
////                query.setPageSize(20);
////                PoiSearch search = new PoiSearch(this, query);
////                search.setBound(new PoiSearch.SearchBound(new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude()), 10000));
////                search.setOnPoiSearchListener(this);
////                search.searchPOIAsyn();
//            }
//        } else
//        {
//            Toast.makeText(mContext, "定位失败",Toast.LENGTH_SHORT).show();
//        }
//    }
    //POISearch成功回调展示
    @Override
    public void onPoiSearched(PoiResult result, int i) {
        PoiSearch.Query query = result.getQuery();
        if (i == 1000) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条

                    ArrayList<PoiItem> pois = result.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    if (pois != null && pois.size() > 0) {
                        mList.clear();
//                        PoiItem poi1 = pois.get(0);
//                        LatLng la = new LatLng(poi1.getLatLonPoint().getLatitude(),
//                                poi1.getLatLonPoint().getLongitude());
//                        mAMap.animateCamera(CameraUpdateFactory.newLatLngZoom(la, 14), 1000, null);
                        for (int j=0;j<pois.size();j++) {
                            PoiItem poi = pois.get(j);
                            String snippet = poi.getSnippet();
                            LocationInfo info = new LocationInfo();
                            if (j==0){
                                info.setSelect(true);
                            }else {
                                info.setSelect(false);
                            }
                            info.setTitle(poi.getTitle());
                            info.setAddress(snippet);
                            LatLonPoint point = poi.getLatLonPoint();
                            info.setLatitude(point.getLatitude());
                            info.setLonTitude(point.getLongitude());
                            info.setAllAddress(poi.getProvinceName()+poi.getCityName()+poi.getAdName());
                            mList.add(info);
                        }
                        mAdapter.setList(mList);
                        mAdapter.notifyDataSetChanged();
                    }
                }
                else {
                    Log.d("dingweiActivity","无结果");
                }
            }
        }  else if (i == 27) {
            Log.e("dingweiActivity","error_network");
        } else if (i == 32) {
            Log.e("dingweiActivity","error_key");
        } else {
            Log.e("dingweiActivity","error_other：" + i);
        }

    }
//POISearch成功回调展示
    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
//        mListener = onLocationChangedListener;
//        //初始化定位
//        mLocationClient = new AMapLocationClient(getApplicationContext());
//        //设置定位回调监听
//        mLocationClient.setLocationListener(this);
//
//        //初始化定位参数
//        mLocationOption = new AMapLocationClientOption();
//        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式、、Hight_Accuracy默认的
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        //设置是否返回地址信息（默认返回地址信息）
//        mLocationOption.setNeedAddress(true);
//        //设置是否只定位一次,默认为false
//        mLocationOption.setOnceLocation(false);
//        //设置是否强制刷新WIFI，默认为强制刷新
//        mLocationOption.setWifiActiveScan(true);
//        //设置是否允许模拟位置,默认为false，不允许模拟位置
//        mLocationOption.setMockEnable(true);
//        //设置定位间隔,单位毫秒,默认为2000ms
//        mLocationOption.setInterval(2000);
//        //给定位客户端对象设置定位参数
//        mLocationClient.setLocationOption(mLocationOption);
//        //启动定位
//        mLocationClient.startLocation();
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null)
        {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
    }

    @Override
    public void onMapClick(LatLng latLng) {
        //        mAMap.clear();
        //        this.custLat = latLng.latitude;
        //        this.custLon = latLng.longitude;
        //
        ////        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        ////        if (!TextUtils.isEmpty(latLonPoint.toString())) {
        ////            getAddress(latLonPoint);
        ////        } else {
        ////            Util.showToast(AttendanceViewMap.this, "拜访地址获取失败");
        ////        }
        //        MarkerOptions otMarkerOptions = new MarkerOptions();
        //        otMarkerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.bd_location_icon01));
        //        otMarkerOptions.position(latLng);
        //        mAMap.addMarker(otMarkerOptions);
    }

    @Override
    public void onMapLoaded() {

    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (marker.isInfoWindowShown())
        {
            marker.hideInfoWindow();

        }
        else
        {
            marker.showInfoWindow();
        }
        return false;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    protected void onResume() {
        super.onResume();
        mMapView.onResume();
        // aMapEx.onRegister();
    }

    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    protected void onDestroy() {
        super.onDestroy();
        // 销毁定位
        if (mLocationClient != null)
        {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        //        if (aMapEx != null) {
        //            aMapEx.onUnregister();
        //        }
        mMapView.onDestroy();
    }

    //通过拖动地图进行位置定位改变，且mark位于屏幕中间不变
    private void setMarket(LatLng latLng, String title, String content) {
        if (mGPSMarker != null)
        {
            mGPSMarker.remove();
        }
        //获取屏幕宽高
        WindowManager wm = this.getWindowManager();
        int width = (wm.getDefaultDisplay().getWidth()) / 2;
        int pxHeight = StringUtils.dip2px(mContext, 289);
        int height = (pxHeight / 2) -20+67;
        markOptions = new MarkerOptions();
        markOptions.draggable(true);//设置Marker可拖动
//        markOptions.icon(BitmapDescriptorFactory.fromBitmap
//                (BitmapFactory.decodeResource(getResources(),
//                        R.mipmap.dingwei_ba))).anchor(0.5f, 0.7f);
        BitmapDescriptor bitmapDescriptor1 = BitmapDescriptorFactory.fromBitmap
                (BitmapFactory.decodeResource(getResources(),
                        R.mipmap.dingwei_ba));//.anchor(0.5f, 0.7f)
        ArrayList<BitmapDescriptor> list=new ArrayList<>();
        list.add(bitmapDescriptor1);
        markOptions.icons(list).anchor(0.5f, 0.7f);
        //设置一个角标
        mGPSMarker = mAMap.addMarker(markOptions);
        //设置marker在屏幕的像素坐标
        mGPSMarker.setPosition(latLng);
        mGPSMarker.setTitle(title);
        mGPSMarker.setSnippet(content);
        //设置像素坐标
        mGPSMarker.setPositionByPixels(width, height);
        //关闭infowindow显示
//        if (!TextUtils.isEmpty(content))
//        {
//            mGPSMarker.showInfoWindow();
//        }
        mMapView.invalidate();
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        latLng=cameraPosition.target;
        double latitude= latLng.latitude;
        double longitude= latLng.longitude;
        Log.e("latitude",latitude+"");
        Log.e("longitude",longitude+"");
        getAddressByLatlng(latLng);
        //显示位置、经纬度
//        tvAdress.setText(addressName);
        latlugStr=latitude + "," + longitude;
        doSearchQuery();
//        tvLnt.setText(latlugStr);
    }

    /**
     * 根据经纬度得到地址
     */
    private void getAddressByLatlng(LatLng latLng) {
        //逆地理编码查询条件：逆地理编码查询的地理坐标点、查询范围、坐标类型。
        LatLonPoint latLonPoint = new LatLonPoint(latLng.latitude, latLng.longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500f, GeocodeSearch.AMAP);
        //异步查询
        geocoderSearch.getFromLocationAsyn(query);
    }
    /**
     * 根据经纬度得到地址
     */
    private void getAddressByLatlng(double latitude,double longitude) {
        //逆地理编码查询条件：逆地理编码查询的地理坐标点、查询范围、坐标类型。
        LatLonPoint latLonPoint = new LatLonPoint(latitude, longitude);
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500f, GeocodeSearch.AMAP);
        //异步查询
        geocoderSearch.getFromLocationAsyn(query);
    }

    /**
     * 逆地理编码回调
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                List<BusinessArea> businessAreas = result.getRegeocodeAddress().getBusinessAreas();
//                String name = businessAreas.get(0).getName();
                addressName = result.getRegeocodeAddress().getFormatAddress(); // 逆转地里编码不是每次都可以得到对应地图上的opi
                L.e("逆地理编码回调  得到的地址：" + addressName);
                List<PoiItem> pois = result.getRegeocodeAddress().getPois();

                setMarket(latLng, "城市", addressName);//
            }
        }
    }

    /**
     * 地理编码查询回调
     */
    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {
        List<GeocodeAddress> geocodeAddressList = result.getGeocodeAddressList();
    }
    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery() {
//        aMap.setOnMapClickListener(null);// 进行poi搜索时清除掉地图点击事件
        int currentPage = 0;
        // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query = new PoiSearch.Query(keyword, deepType, "");
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        LatLonPoint lp = new LatLonPoint(latLng.latitude, latLng.longitude);
        try{
            poiSearch = new PoiSearch(this, query);
        }catch (Exception e){
            e.printStackTrace();
        }
        poiSearch.setOnPoiSearchListener(this);
        // 设置搜索区域为以lp点为圆心，其周围2000米范围
        poiSearch.setBound(new PoiSearch.SearchBound(lp, 3000*1000, true));
        poiSearch.searchPOIAsyn();// 异步搜索

    }

}
